package com.easybuy.controller;

import com.easybuy.pojo.User;
import com.easybuy.service.UserService.UserService;
import com.ndktools.javamd5.Mademd5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
//登录、注册、注销
public class LoginController {
    @Autowired
    private UserService userService;

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public Map login(@RequestParam String loginName, @RequestParam String passWord, HttpSession session){
        System.out.println(loginName+"\n"+passWord);
        Mademd5 md5=new Mademd5();
        passWord=md5.toMd5(passWord).toLowerCase();
        Map map=new HashMap();
        User user=userService.selectByLoginName(loginName);
        map.put("user",user);
        if(user==null){
            System.out.println(1);
            map.put("state",1);
            return map;
        }else if (!passWord.equals(user.getPassword())){
            System.out.println(passWord);
            System.out.println(user.getPassword());
            map.put("state",2);
            return map;
        }else {
            session.setAttribute("user",user);
            System.out.println(3);
            map.put("state",3);
            return map;
        }
    }
    //注册
    @RequestMapping("/regist")
    @ResponseBody
    public Boolean regist(User user){
        Mademd5 md5=new Mademd5();
        String password=md5.toMd5(user.getPassword()).toLowerCase();
        user.setPassword(password);
        if(userService.addUser(user)>0){
            return true;
        }else {
            return false;
        }
    }
    //注销
    @RequestMapping("/logout")
    @ResponseBody
    public void logout(HttpSession session){
        session.invalidate();
    }

    public void tt(HttpServletRequest request){

    }
}
